#include "Tool.h"

Tool::Tool(void)
{
    moveType = 0;
}

Tool::~Tool(void)
{
}

void Tool::createAnimate(CCAnimation* animation)
{
    ccAnimation = *animation;
}

CCRect Tool::rect()
{
    CCSize s = getTexture()->getContentSize();
    return CCRectMake(0, 0 , s.width, s.height);
}

bool Tool::initWithTexture(CCTexture2D* aTexture)
{
    if( CCSprite::initWithTexture(aTexture) )
    {
        t_state = kToolStateUngrabbed;
    }
    
    return true;
}

void Tool::onEnter()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
    CCSprite::onEnter();
}

void Tool::onExit()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->removeDelegate(this);
    CCSprite::onExit();
}

bool Tool::containsTouchLocation(CCTouch* touch)
{
    return rect().containsPoint(convertTouchToNodeSpaceAR(touch));
}

bool Tool::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    if (t_state != kToolStateUngrabbed) return false;
    if (containsTouchLocation(touch)){        
        CCAnimation* animation = CCAnimation::create();
        for( int i=0;i<animateCount;i++)
        {
            char szName[100] = {0};
            sprintf(szName, animateString.c_str(), i);
            animation->addSpriteFrameWithFileName(szName);
        }
        animation->setDelayPerUnit(0.3f / 3.0f);
        animation->setRestoreOriginalFrame(true);
        CCAnimate *animate = CCAnimate::create(animation);
        runAction(CCRepeatForever::create(animate));
        
        CCPoint touchPoint = touch->getLocation();
        px = rectWidth - touchPoint.x + positionX;
        py = rectHeight - touchPoint.y + positionY;
        
        setAnchorPoint(ccp((touchPoint.x - positionX)/getContentSize().width,(touchPoint.y - positionY)/getContentSize().height));
        setPosition(ccp(touchPoint.x, touchPoint.y));
        moveType = 1;
        setZOrder(7);
    }else{
        return false;
    }
    
    t_state = kToolStateGrabbed;
    return true;
}

void Tool::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
    CCPoint touchPoint = touch->getLocation();
//    CCLOG("CCPoint1: %s %f %s %f \n", "x:", touchPoint.x, "y:", touchPoint.y);
    setPosition(ccp(touchPoint.x, touchPoint.y));
}

void Tool::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
    stopAllActions();
    CCLOG("this is %s", imageName.c_str());
    CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(imageName.c_str());
    this->setTexture(texture);
    
    setAnchorPoint(ccp(0,0));
    setPosition(ccp(positionX,positionY));
    moveType = 0;
    t_state = kToolStateUngrabbed;
}

void Tool::touchDelegateRetain()
{
    this->retain();
}

void Tool::touchDelegateRelease()
{
    this->release();
}